<?php
/**
 * Introduction: 微信支付
 * @author: 林小平
 * @date: 2016/4/7 23:00
 * @email: linxiaoping@cdlinglu.com
 */

namespace Think\Wxpay;


use Common\Model\MemberOtherPlatformModel;
use Think\Exception;
use Think\Wxpay\Driver;
use Think\Wxpay\DriverApp;


class Wxpay
{


    /**
     * 微信公众号支付退款
     * @param $out_trade_no   订单号
     * @param $total_fee  订单金额
     * @param $refund_fee 退款金额
     */
    static public function WeChatrefund($out_trade_no,$total_fee,$refund_fee){
        $input = new Driver\WxPayUnifiedOrder();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no(time());
        $input->SetOp_user_id(time());
        $pay_api = new Driver\WxPayApi();
        //$result = DriverApp\WxPayApi::refund($input);
        $result = $pay_api->refund($input);
    }

    /**
     * Introduction: H5 APP支付生成签名字符串()
     * @param array or string $out_trade_no 订单ID 必须包含
     * @param intval $total 支付金额 必须包含
     * @param string $subject 商品名称 必须包含
     */
    static public function signH5($out_trade_no,$total,$subject,$attach='')
    {


        if(is_array($out_trade_no)){

            $total = $out_trade_no['total'];
            $subject = $out_trade_no['subject'];
            $out_trade_no = $out_trade_no['out_trade_no'];

        }

        if(!$total)
            return ['code' => 300, 'msg' => '缺少金额!'];

        if(!$subject)
            return ['code' => 300, 'msg' => '缺少商品名称!'];

        if(!$out_trade_no)
            return ['code' => 300, 'msg' => '缺少订单ID!'];

        // 获取支付金额
        $total = floatval($total);

        $unifiedOrder = new DriverApp\WxPayUnifiedOrder();

        $unifiedOrder->SetBody($subject);//商品或支付单简要描述

        $unifiedOrder->SetOut_trade_no($out_trade_no);

        $unifiedOrder->SetAttach($attach);//设置自定义参数

        $unifiedOrder->SetTotal_fee($total);

        $unifiedOrder->SetTrade_type(C('WeChat_APP.TRADE_TYPE'));

        $result = DriverApp\WxPayApi::unifiedOrder($unifiedOrder);

        if(isset($result['code']) && $result['code'] == 300)
            return $result;

        if (is_array($result)) {

            return ['code' => 200, 'data'=> ['url' => json_encode($result)]];

        }

    }
    /**
     * Introduction: H5 APP支付生成签名字符串()
     * @param array or string $out_trade_no 订单ID 必须包含
     * @param intval $total 支付金额 必须包含
     * @param string $subject 商品名称 必须包含
     */
    static public function signapp($out_trade_no,$total='',$subject='',$attach='')
    {


        if(is_array($out_trade_no)){

            $total = $out_trade_no['order_amount'];
            $subject = $out_trade_no['buyer_name'];
            $out_trade_no = $out_trade_no['order_id'];

        }

        if(!$total)
            return ['code' => 300, 'msg' => '缺少金额!'];

        if(!$subject)
            return ['code' => 300, 'msg' => '缺少商品名称!'];

        if(!$out_trade_no)
            return ['code' => 300, 'msg' => '缺少订单ID!'];

        // 获取支付金额
        $total = floatval($total);

        $unifiedOrder = new DriverApp\WxPayUnifiedOrder();

        $unifiedOrder->SetBody($subject);//商品或支付单简要描述

        $unifiedOrder->SetOut_trade_no($out_trade_no);

        $unifiedOrder->SetAttach($attach);//设置自定义参数

        $unifiedOrder->SetTotal_fee($total);

        $unifiedOrder->SetTrade_type(C('WeChat_APP.TRADE_TYPE'));

        $result = DriverApp\WxPayApi::unifiedOrder($unifiedOrder);

        if(isset($result['code']) && $result['code'] == 300)
            return $result;

        if (is_array($result)) {

            return ['code' => 200, 'data'=>  $result];

        }

    }
    /**
     * Introduction: 微信端支付生成签名()
     * @param array or string $out_trade_no 订单ID 必须包含
     * @param intval $total 支付金额 必须包含
     * @param string $subject 商品名称 必须包含
     */
    public function WeChatPay($order_info,$code)
    {
        //获取订单信息
//        array(
//
//            'buyer_name',//设置商品名称
//            'order_sn',//设置商户系统内部的订单号
//            'order_amount',//设置订单总金额
//
//        )

        if(!$order_info['buyer_name'])
            return ['code' => 300, 'msg' => '缺少商品名称'];

        if(!$order_info['order_id'])
            return ['code' => 300, 'msg' => '缺少订单ID'];

        if(!$order_info['order_amount'])
            return ['code' => 300, 'msg' => '缺少订单金额'];


        //获取配置
        $config = C('WeChat_WeChat');
        //获取用户openid
        $tools = new Driver\JsApiPay();
        $member_id = session('member_id');
        $model = new MemberOtherPlatformModel();
        $user_info = $model->where("userid=$member_id")->field("data")->find();
        $user_data = json_decode($user_info['data'],true);
        $open_id = session('open_id');//$tools->GetOpenid($code);
        if(empty($open_id)){
            $open_id = $user_data['openid'];
        }

        //下单配置
        $input = new Driver\WxPayUnifiedOrder();

        //设置商品或支付单简要描述
        $input->SetBody($order_info['buyer_name']);//设置商品名称

        //设置附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        //$input->SetAttach($order_info['order_sn']);//设置自定义参数

        //设置商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
        //防止订单号重复下单
        $input->SetOut_trade_no($order_info['order_id']);

        //设置订单总金额，只能为整数，详见支付金额
        $input->SetTotal_fee(floatval($order_info['order_amount']));//支付金额

        //设置订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
        $input->SetTime_start(date("YmdHis",NOW_TIME));

        //设置订单失效时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
        $input->SetTime_expire(date("YmdHis", NOW_TIME + 1200));

        //设置商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
        //$input->SetGoods_tag($order_info['store_name']);

        //设置接收微信支付异步通知回调地址
        $input->SetNotify_url($config['NOTIFY_URL']);

        //设置取值如下：JSAPI，NATIVE，APP，详细说明见参数规定
        $input->SetTrade_type($config['TRADE_TYPE']);

        //设置trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识。下单前需要调用【网页授权获取用户信息】接口获取到用户的Openid。
        $input->SetOpenid($open_id);


        $pay_api = new Driver\WxPayApi();

        $order = $pay_api->unifiedOrder($input,6);
       // $order = $pay_api->unifiedOrder($input,6,$config);

        if(isset($order['code']) && $order['code'] == 300)
            return $order;


        try {

            $jsApiParameters = $tools->GetJsApiParameters($order);

            return ['code' => 200, 'data' => $jsApiParameters];

        } catch (Exception $e) {

            return ['code' => 300, 'msg' => $e->getMessage()];

        }




    }

    /**
     * Introduction: 微信端获取用户用户信息
     */
    public function getUserInfo($code){

        $tools = new Driver\JsApiPay();

        return $tools->GetUserInfo($code);

    }

    /**
     * Introduction: 微信端获取用户openid    unionid
     * @param $code
     * @return Driver\用户的openid
     */

    public function getOpenId($code){

        $tools = new Driver\JsApiPay();

        return $tools->GetOpenid($code);

    }

    /**
     * Introduction: 微信端获取用户unionid
     * @param $code
     * @return Driver\用户的unionid
     */

    public function GetUnionid($code){

        $tools = new Driver\JsApiPay();

        return $tools->GetUnionid($code);

    }
    /**
     * Introduction: 获取jsApi
     */
    public function getJsSdk(){

        $js_sdk = new Driver\JsSdk();

        return $js_sdk->getJsSdk();

    }
    /**
     * Introduction: 微信上传抓去图片
     */
    public function getWeChatImage($media_id)
    {

        if(!$media_id)
            return ['code' => 300, 'msg' => '缺少media_id'];

        $media_id = explode(',',trim($media_id,','));

        $js_sdk = new Driver\JsSdk();

        $access_token = $js_sdk->_getAccessToken();

        $data = [];

        $path = '/upload/wechat/'.date("Ymd",time()).'/';

        if (!is_dir(APP_PATH.$path)) {

            mkdir(APP_PATH.$path, 0777, true);

        }

        foreach($media_id as $k => $v){

            $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" . $access_token . "&media_id=" . $v;


            $ch = curl_init();

            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
            curl_setopt($ch, CURLOPT_NOBODY, FALSE);
            curl_setopt($ch, CURLOPT_URL, $url);
            ob_start();
            curl_exec($ch);

            $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if ($return_code != 200) {

                $data[$k] = '';

            }

            $response = ob_get_contents();
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

            ob_end_clean();

            $header = substr($response, 0, $headerSize);

            $body = substr($response, $headerSize);

            preg_match_all('/filename="[^.]+.(\w+)"/s', $header, $arr);

            $ext = $arr[1][0];

            //file_put_contents(APP_PATH.'/upload/header_'.$k.'.log',json_encode($header));
            //file_put_contents(APP_PATH.'/upload/body_'.$k.'.log',json_encode($body));

            //error_log($header);
            //error_log($body);

            $filename = $path. date("YmdHis",time()) . rand(1000, 9999) . ".$ext";

            //$targetName = APP_PATH . $filename;

            $fp = @fopen(APP_PATH.$filename, "w+");

            // 保存文件
            fwrite($fp, $body);

            fclose($fp);

            $data[$k] = $filename;
        }

        return  ['code' => 200, 'data' => ['lists' => $data]];

    }

    /**
     * Introduction: 获取jsApi
     */
    public function getJsApiTicket(){

        $js_sdk = new Driver\JsSdk();

        return $js_sdk->_getJsApiTicket();

    }

    /**
     * Introduction: APP微信回调数据解析
     */
    public function WxPayAppResults($data){

        $result = new DriverApp\WxPayResults();

        return $result->Init($data);

    }

    /**
     * Introduction: 微信回调数据解析
     */
    public function WxPayResults($data){

        $result = new Driver\WxPayResults();

        return $result->Init($data);

    }

}